/**
 * 功能：
 * 1. 传入 items 属性，使 TableFilterForm 可配置
 * 2. 传入 onSearch、onReset 属性，监听查询按钮、重置按钮点击事件
 */
import React, {
    useState,
    useEffect,
    useImperativeHandle,
    forwardRef,
    useRef
} from 'react';
import { Form, Button } from 'antd';
// import { HcpTenantFilterSelect, HcpCloudAccountSelect } from '@/components';
import {
    DoubleRightOutlined,
    UndoOutlined,
    SearchOutlined,
    SyncOutlined,
} from '@ant-design/icons';

const LabelText = ({ text }) => (
    <div style={{ display: 'inline-block' }}>{text}</div>
);

let HcpTableFilterBar = (
    {
        form,
        commonItems = [],
        items = [],
        onSearch,
        restProps,
        resetClick,
        showSearch = true,
        showReset = true,
        showRefresh = false,
        masterTenantChange //用于在租户发生变化的时候，执行对应的请求操作
    },
    ref
) => {
    const [tenantRef, setTenantRef] = useState(useRef())
    // 监听查询按钮点击
    const handleSearch = (values) => {
        onSearch(values);
    };

    // 监听重置按钮点击
    const handleReset = () => {
        let keys = Object.keys(form.getFieldValue());
        form.resetFields(keys);
        resetClick && resetClick();
    };
    // 监听刷新按钮点击
    const handleRefresh = () => {
        onSearch(values);
    };

    // 渲染表单项
    // const renderFormItems = () => {
    //   return items.map(item => {
    //     const { label, style, field, options, component } = item;
    //     return (
    //       <Form.Item
    //         style={{
    //           float: 'right',
    //           marginRight: 10,
    //           ...style
    //         }}
    //         label={label&&<LabelText text={label} />}
    //         key={field}
    //         name={field}
    //         {...options}
    //       >
    //         {component}
    //       </Form.Item>
    //     );
    //   });
    // }

    const onMasterTenantChange = (value, p, j, flag) => {
        !flag && form.setFieldsValue({
            masterTenantId: value,
            tenantId: undefined,
        });
        tenantRef.current?.onSearch({ masterTenantId: value });
        masterTenantChange && masterTenantChange();
    }

    const onValuesChange = (field) => {
        let key = Object.keys(field)[0];
        let v = field[key];
        if (v === "" || (Array.isArray(v) && v.length === 0)) form.setFieldValue(key, undefined); // 搜索时空值清空字段
    }

    const masterTenantForm = (commonItems, items, form) => {
        commonItems?.map((item) => {
            const { columnIndex, field, isHide, superStyle, withall = false, className, value, params} = item;
            let obj = {
                field,
                isHide,
                style: { width: '170px' },
                superStyle,
                component: null,
                value,
                params
            };
            // if (field == 'masterTenantId') {
            //     obj.component = (
            //         <HcpTenantFilterSelect placeholder="租户" handleChange={onMasterTenantChange}  withall={withall} className={className} value={value} showSelectUser={Boolean(value)}/>
            //     )
            // } else if (field == 'tenantId') {
            //     obj.component = (
            //         <HcpCloudAccountSelect cRef={tenantRef} placeholder="云账号" defaultValue={value} tenantIdLimit  withall={withall} params={params}/>
            //     )
            // }
            if (obj.component) items.splice(columnIndex, 0, obj);
        })

        return items;
    }

    const renderFormItems = () => {
        const newItems = masterTenantForm(commonItems, items, form);
        const size = newItems?.length ?? 0;
        return newItems.map((item, index) => {
            // 由于ui规范制定搜索框都为240px 给特别的地方指定width的机会
            let { style, field, label, component, initialValue, superStyle, isHide } = item;
            if (isHide) return null;

            return (
                <Form.Item
                    style={{
                        float: 'right',
                        marginRight: 10,
                        ...style,
                        width: superStyle?.width || (size >= 4 ? (index === 0 ? '240px' : '160px') : '240px'),
                        display: field === 'projectId' ? 'none' : 'block'
                    }}
                    label={label}
                    initialValue={initialValue}
                    key={field}
                    name={field}
                >
                    {component}
                </Form.Item>
            );
        });
    };

    // 渲染按钮组
    const renderButtons = () => {
        return (
            <Form.Item style={{ float: 'right', marginRight: 0 }}>
                {showSearch ? (
                    <Button
                        style={{ marginRight: 10 }}
                        type="primary"
                        htmlType="submit"
                        icon={<SearchOutlined />}
                    />
                ) : (
                    ''
                )}
                {showReset ? (
                    <Button
                        onClick={handleReset}
                        icon={<UndoOutlined />}
                    />
                ) : (
                    ''
                )}
                {showRefresh ? (
                    <Button
                        icon={<SyncOutlined />}
                        onClick={handleRefresh}
                    />
                ) : (
                    ''
                )}
            </Form.Item>
        );
    };

    return (
        <div {...restProps} style={{ width: '100%' }}>
            <Form
                form={form}
                className
                layout="horizontal"
                noValidate
                autoComplete="off"
                onFinish={handleSearch}
                onValuesChange={onValuesChange}
            >
                {renderButtons()}
                {renderFormItems()}
                {/* 清楚浮动 */}
                <div style={{ clear: 'both' }} />
            </Form>
        </div>
    );
};

HcpTableFilterBar = forwardRef(HcpTableFilterBar);

export default React.memo(HcpTableFilterBar);
